package com.zlict.admin.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.zlict.common.core.domain.model.LoginUser;
import com.zlict.common.utils.SecurityUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.zlict.common.annotation.Log;
import com.zlict.common.core.controller.BaseController;
import com.zlict.common.core.domain.AjaxResult;
import com.zlict.common.enums.BusinessType;
import com.zlict.admin.domain.RdWorkhours;
import com.zlict.admin.service.IRdWorkhoursService;
import com.zlict.common.utils.poi.ExcelUtil;
import com.zlict.common.core.page.TableDataInfo;

/**
 * 考勤工时Controller
 * 
 * @author ruoyi
 * @date 2025-06-11
 */
@RestController
@RequestMapping("/system/workhours")
public class RdWorkhoursController extends BaseController
{
    @Autowired
    private IRdWorkhoursService rdWorkhoursService;

    /**
     * 查询考勤工时列表
     */
    //@PreAuthorize("@ss.hasPermi('system:workhours:list')")
    @GetMapping("/list")
    public TableDataInfo list(RdWorkhours rdWorkhours)
    {
        startPage();
        List<RdWorkhours> list = rdWorkhoursService.selectRdWorkhoursList(rdWorkhours);
        return getDataTable(list);
    }


    /**
     * 根据人和月查询考勤工时列表
     * @param rdWorkhours
     * @return
     */
    @GetMapping("/wklist")
    public TableDataInfo wklist(RdWorkhours rdWorkhours)
    {
        startPage();
        List<RdWorkhours> list = rdWorkhoursService.selectRdWorkhoursByUserList(rdWorkhours);
        return getDataTable(list);
    }

    /**
     * 导出考勤工时列表
     */
    //@PreAuthorize("@ss.hasPermi('system:workhours:export')")
    @Log(title = "考勤工时", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RdWorkhours rdWorkhours)
    {
        List<RdWorkhours> list = rdWorkhoursService.selectRdWorkhoursList(rdWorkhours);
        ExcelUtil<RdWorkhours> util = new ExcelUtil<RdWorkhours>(RdWorkhours.class);
        util.exportExcel(response, list, "考勤工时数据");
    }

    /**
     * 获取考勤工时详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:workhours:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(rdWorkhoursService.selectRdWorkhoursById(id));
    }

    /**
     * 新增考勤工时
     */
    //@PreAuthorize("@ss.hasPermi('system:workhours:add')")
    @Log(title = "考勤工时", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RdWorkhours rdWorkhours)
    {
        return toAjax(rdWorkhoursService.insertRdWorkhours(rdWorkhours));
    }

    /**
     * 修改考勤工时
     */
    //@PreAuthorize("@ss.hasPermi('system:workhours:edit')")
    @Log(title = "考勤工时", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RdWorkhours rdWorkhours)
    {
        LoginUser loginUser = getLoginUser();
        return toAjax(rdWorkhoursService.updateRdWorkhours(rdWorkhours));
    }

    /**
     * 删除考勤工时
     */
    //@PreAuthorize("@ss.hasPermi('system:workhours:remove')")
    @Log(title = "考勤工时", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(rdWorkhoursService.deleteRdWorkhoursByIds(ids));
    }

    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("工时模板");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"工号", "姓名", "年月"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 添加1-31的列
            for (int i = 1; i <= 31; i++) {
                Cell cell = headerRow.createCell(headers.length + i - 1);
                cell.setCellValue(String.valueOf(i));
            }

            // 创建标题行样式
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            headerStyle.setBorderTop(BorderStyle.THIN);
            headerStyle.setBorderBottom(BorderStyle.THIN);
            headerStyle.setBorderLeft(BorderStyle.THIN);
            headerStyle.setBorderRight(BorderStyle.THIN);

            // 创建标题字体
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short) 12);
            headerStyle.setFont(headerFont);

            // 应用样式到所有标题单元格
            for (int i = 0; i < headers.length + 31; i++) {
                Cell cell = headerRow.getCell(i);
                cell.setCellStyle(headerStyle);
            }

            // 为年月列添加批注
            Drawing<?> drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 2, 0, 3, 1);
            Comment comment = drawing.createCellComment(anchor);
            comment.setString(new XSSFRichTextString("格式为yyyy-MM(例如:2025-01)"));
            headerRow.getCell(2).setCellComment(comment);

            // 创建日期格式
            DataFormat format = workbook.createDataFormat();
            CellStyle dateStyle = workbook.createCellStyle();
            dateStyle.setDataFormat(format.getFormat("yyyy年m月"));
            dateStyle.setAlignment(HorizontalAlignment.CENTER);
            dateStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            dateStyle.setBorderTop(BorderStyle.THIN);
            dateStyle.setBorderBottom(BorderStyle.THIN);
            dateStyle.setBorderLeft(BorderStyle.THIN);
            dateStyle.setBorderRight(BorderStyle.THIN);

            // 设置列宽
            for (int i = 0; i < headers.length + 31; i++) {
                sheet.setColumnWidth(i, 15 * 256);
            }

            // 设置行高
            headerRow.setHeight((short) (20 * 20));

            // 冻结首行
            sheet.createFreezePane(0, 1);

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=workhours_template.xlsx");

            // 写入响应流
            workbook.write(response.getOutputStream());
        }
    }


    //@PreAuthorize("@ss.hasPermi('system:workhours:export')")
    @Log(title = "考勤工时", businessType = BusinessType.EXPORT)
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(@RequestParam(required = true) String month, HttpServletResponse response) throws IOException {
        try {
            // 验证月份格式
            if (!month.matches("\\d{4}-\\d{2}")) {
                throw new RuntimeException("月份格式不正确，请使用yyyy-MM格式");
            }

            // 解析年月
            String[] yearMonth = month.split("-");
            int year = Integer.parseInt(yearMonth[0]);
            int monthNum = Integer.parseInt(yearMonth[1]);

            // 验证月份范围
            if (monthNum < 1 || monthNum > 12) {
                throw new RuntimeException("月份必须在1-12之间");
            }

            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("考勤工时导入模板");

            // 设置列宽
            sheet.setColumnWidth(0, 15 * 256); // 工号
            sheet.setColumnWidth(1, 15 * 256); // 姓名

            // 创建样式
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            headerStyle.setBorderTop(BorderStyle.THIN);
            headerStyle.setBorderBottom(BorderStyle.THIN);
            headerStyle.setBorderLeft(BorderStyle.THIN);
            headerStyle.setBorderRight(BorderStyle.THIN);
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);

            // 创建周末样式
            CellStyle weekendStyle = workbook.createCellStyle();
            weekendStyle.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
            weekendStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            weekendStyle.setAlignment(HorizontalAlignment.CENTER);
            weekendStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            weekendStyle.setBorderTop(BorderStyle.THIN);
            weekendStyle.setBorderBottom(BorderStyle.THIN);
            weekendStyle.setBorderLeft(BorderStyle.THIN);
            weekendStyle.setBorderRight(BorderStyle.THIN);
            Font weekendFont = workbook.createFont();
            weekendFont.setColor(IndexedColors.RED.getIndex());
            weekendStyle.setFont(weekendFont);

            // 创建表头行
            Row headerRow = sheet.createRow(0);
            headerRow.setHeight((short) (20 * 20));

            // 添加工号和姓名列
            String[] headers = {"工号", "姓名"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 获取当月天数
            Calendar calendar = Calendar.getInstance();
            calendar.set(year, monthNum - 1, 1);
            int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

            // 添加日期列
            for (int day = 1; day <= daysInMonth; day++) {
                calendar.set(year, monthNum - 1, day);
                int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                boolean isWeekend = (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY);

                // 设置列宽
                sheet.setColumnWidth(headers.length + day - 1, 15 * 256);

                // 设置表头和日期
                Cell headerCell = headerRow.createCell(headers.length + day - 1);
                headerCell.setCellValue(String.format("%d-%02d-%02d", year, monthNum, day));
                headerCell.setCellStyle(isWeekend ? weekendStyle : headerStyle);
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("考勤工时导入模板", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 写入响应
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            //log.error("下载模板失败", e);
            throw new RuntimeException("下载模板失败：" + e.getMessage());
        }
    }
    /**
     * 下载工时导入模板
     */
//    @GetMapping("/downloadTemplate")
//    public void downloadTemplate(HttpServletResponse response) throws IOException {
//        try (Workbook workbook = new XSSFWorkbook()) {
//            Sheet sheet = workbook.createSheet("工时模板");
//
//            // 创建标题行
//            Row headerRow = sheet.createRow(0);
//            String[] headers = {"工号", "姓名", "年月"};
//            for (int i = 0; i < headers.length; i++) {
//                Cell cell = headerRow.createCell(i);
//                cell.setCellValue(headers[i]);
//            }
//
//            // 添加1-31的列
//            for (int i = 1; i <= 31; i++) {
//                Cell cell = headerRow.createCell(headers.length + i - 1);
//                cell.setCellValue(String.valueOf(i));
//            }
//
//            // 创建标题行样式
//            CellStyle headerStyle = workbook.createCellStyle();
//            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
//            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//            headerStyle.setAlignment(HorizontalAlignment.CENTER);
//            headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//            headerStyle.setBorderTop(BorderStyle.THIN);
//            headerStyle.setBorderBottom(BorderStyle.THIN);
//            headerStyle.setBorderLeft(BorderStyle.THIN);
//            headerStyle.setBorderRight(BorderStyle.THIN);
//
//            // 创建标题字体
//            Font headerFont = workbook.createFont();
//            headerFont.setBold(true);
//            headerFont.setFontHeightInPoints((short) 12);
//            headerStyle.setFont(headerFont);
//
//            // 应用样式到所有标题单元格
//            for (int i = 0; i < headers.length + 31; i++) {
//                Cell cell = headerRow.getCell(i);
//                cell.setCellStyle(headerStyle);
//            }
//
//            // 为年月列添加批注
//            Drawing<?> drawing = sheet.createDrawingPatriarch();
//            ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 2, 0, 3, 1);
//            Comment comment = drawing.createCellComment(anchor);
//            comment.setString(new XSSFRichTextString("格式为yyyy-MM(例如:2025-01)"));
//            headerRow.getCell(2).setCellComment(comment);
//
//            // 创建日期格式
//            DataFormat format = workbook.createDataFormat();
//            CellStyle dateStyle = workbook.createCellStyle();
//            dateStyle.setDataFormat(format.getFormat("yyyy年m月"));
//            dateStyle.setAlignment(HorizontalAlignment.CENTER);
//            dateStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//            dateStyle.setBorderTop(BorderStyle.THIN);
//            dateStyle.setBorderBottom(BorderStyle.THIN);
//            dateStyle.setBorderLeft(BorderStyle.THIN);
//            dateStyle.setBorderRight(BorderStyle.THIN);
//
//            // 设置列宽
//            for (int i = 0; i < headers.length + 31; i++) {
//                sheet.setColumnWidth(i, 15 * 256);
//            }
//
//            // 设置行高
//            headerRow.setHeight((short) (20 * 20));
//
//            // 冻结首行
//            sheet.createFreezePane(0, 1);
//
//            // 设置响应头
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setHeader("Content-Disposition", "attachment; filename=workhours_template.xlsx");
//
//            // 写入响应流
//            workbook.write(response.getOutputStream());
//        }
//    }

    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws IOException {
        try {
            //int result = rdWorkhoursService.importData(file);
            Map<String,Object> map = rdWorkhoursService.importData(file);
            return success(map);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
